package net.chenlin.dp.common.utils;

import net.chenlin.dp.common.constant.MsgConstant;
import net.chenlin.dp.common.constant.SystemConstant;
import net.chenlin.dp.common.entity.R;
import org.apache.commons.lang.StringUtils;

import java.util.Map;

/**
 * 通用工具类
 * @author zcl<yczclcn@163.com>
 */
public class CommonUtils {

	/**
	 * 对象是否为空
	 * 
	 * @param obj
	 * @return
	 */
	public static boolean isNullOrEmpty(Object obj) {
		if (obj == null) {
			return true;
		}
		return false;
	}

	/**
	 * 判断整数是否大于零
	 * 
	 * @param number
	 * @return
	 */
	public static boolean isIntThanZero(int number) {
		if (number > 0) {
			return true;
		}
		return false;
	}
	
	/**
	 * 新增，修改提示
	 * @param count
	 * @return
	 */
	public static R msg(int count) {
		if(isIntThanZero(count)){
			return R.ok(MsgConstant.MSG_OPERATION_SUCCESS);
		}
		return R.error(MsgConstant.MSG_OPERATION_FAILED);
	}
	
	/**
	 * 查询详情提示
	 * @param data
	 * @return
	 */
	public static R msg(Object data) {
		if(isNullOrEmpty(data)){
			return R.error(MsgConstant.MSG_INIT_FORM);
		}
		return R.ok().put(SystemConstant.DATA_ROWS, data);
	}
	
	/**
	 * 返回数据
	 * @param data
	 * @return
	 */
	public static R msgNotCheckNull(Object data) {
		return R.ok().put(SystemConstant.DATA_ROWS, data);
	}
	
	/**
	 * 删除提示
	 * @param total
	 * @param count
	 * @return
	 */
	public static R msg(Object[] total, int count) {
		if(total.length == count){
			return R.ok(MsgConstant.MSG_OPERATION_SUCCESS);
		}else{
			if(isIntThanZero(count)){
				return R.error(MsgConstant.removeFailed(total.length, count));
			}else{
				return R.error(MsgConstant.MSG_OPERATION_FAILED);
			}
		}
	}

	/**
	 * SQL模糊查询特殊字符转义(%,_)
	 * @param keyword
	 * @return
	 */
	public static String fixSpecialForLike(String keyword) {
		if (StringUtils.isNotBlank(keyword)) {
			char[] keys = keyword.toCharArray();
			StringBuilder sb = new StringBuilder();
			for (char key : keys) {
				if (key == '%' || key == '_') {
					sb.append('\\');
				}
				sb.append(key);
			}
			return sb.toString();
		}
		return null;
	}

	/**
	 * SQL模糊查询特殊字符转义
	 * @param params 参数map
	 * @param keys 需要转义的参数key
	 * @return
	 */
	public static Map<String, Object> fixSpecialForLike(Map<String, Object> params, String... keys) {
		if (keys.length == 0) {
			return params;
		}
		for (String key : keys) {
			Object value = params.get(key);
			if (value != null) {
				params.put(key, fixSpecialForLike(String.valueOf(value)));
			}
		}
		return params;
	}
	
}
